import { locationContext } from '@/contexts/locationContext'
import { ChevronLeft } from 'lucide-react'
import { useContext, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate, useParams } from 'react-router-dom'
import { Button } from '../../components/ui/button'
import { getReportFormApi } from '../../controllers/API/flow'
import { uploadFileWithProgress } from '../../modals/UploadModal/upload'
import LabelPanne from './components/Label'
import Word from './components/Word'

export default function Report() {
  const { t } = useTranslation()

  const { appConfig } = useContext(locationContext)
  const navigate = useNavigate()
  const { docx, loading, createDocx, importDocx } = useReport()

  // inset var
  const iframeRef = useRef(null)
  const handleInset = value => {
    if (!iframeRef.current) return
    const iframeDom = iframeRef.current.querySelector('iframe')
    if (!iframeDom) return
    iframeDom.contentWindow.postMessage(
      JSON.stringify({
        type: 'onExternalPluginMessage',
        action: 'insetMarker',
        data: value
      }),
      appConfig.officeUrl
    )
  }

  return (
    <div className="">
      {loading && (
        <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
          <span className="loading loading-infinity loading-lg"></span>
        </div>
      )}
      <div className="absolute top-0 flex h-10 w-full items-center justify-center ">
        <span
          className="absolute left-10 flex cursor-pointer items-center gap-1 text-gray-600 hover:text-gray-500"
          onClick={() => navigate(-1)}
        >
          <ChevronLeft size={20} />
          {t('back')}
        </span>
        <span className="text-sm">docx</span>
      </div>
      <div className="flex h-screen gap-4 bg-gray-50 p-10">
        <div ref={iframeRef} className="flex flex-1 items-center justify-center border bg-[#fff]">
          {docx.path ? (
            // office
            <Word data={docx}></Word>
          ) : (
            // create
            <div className="w-full max-w-[650px] rounded-md border bg-gray-50 p-8 py-10">
              <p className="text-xl">{t('report.reportTemplate')}</p>
              <p className="mt-2 text-sm">{t('report.reportDescription')}</p>
              <div className="mt-4 flex gap-2">
                <Button size="sm" className="w-full" onClick={createDocx}>
                  {t('report.newButton')}
                </Button>
                <Button
                  variant="secondary"
                  disabled={loading}
                  size="sm"
                  className="w-full border-gray-200"
                  onClick={importDocx}
                >
                  {loading && <span className="loading loading-spinner loading-sm pointer-events-none h-8 pl-3"></span>}
                  {t('report.importButton')}
                </Button>
              </div>
            </div>
          )}
        </div>
        <div className="w-[240px] overflow-y-auto border bg-[#fff] px-4 pt-4">
          <LabelPanne onInset={handleInset}></LabelPanne>
        </div>
      </div>
    </div>
  )
}

const useReport = () => {
  const [loading, setLoading] = useState(false)

  const [docx, setDocx] = useState({
    key: '',
    path: ''
  })
  // 获取编辑的文档
  const { id } = useParams()
  useEffect(() => {
    setLoading(true)
    getReportFormApi(id).then(({ version_key, temp_url }) => {
      setLoading(false)
      setDocx({
        key: version_key,
        path: temp_url
      })
    })
  }, [id])

  const handleCreate = () => {
    setDocx({
      ...docx,
      // path: 'http://192.168.106.120:3002/empty.docx'
      path: location.origin + '/empty.docx' // 文档服务能访问到的文件地址
    })
  }

  const handleImport = () => {
    // 上传
    // Create a file input element
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = '.doc, .docx'
    input.style.display = 'none' // Hidden from view
    input.multiple = false // Allow only one file selection

    input.onchange = (e: Event) => {
      setLoading(true)

      // Get the selected file
      const file = (e.target as HTMLInputElement).files?.[0]
      uploadFileWithProgress(file, progress => {}).then(res => {
        setLoading(false)
        setDocx({
          ...docx,
          path: res.file_path
        })
      })
    }

    input.click()
  }

  return {
    loading,
    docx,
    createDocx: handleCreate,
    importDocx: handleImport
  }
}
